import axios from "axios";
import { MessageBox, Message } from "element-ui";
import { getToken } from "./auth.js";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import _this from "../main.js";
import store from "@/store";
// create an axios instance
const service = axios.create({
  //baseURL: "https://localhost:44311",
  //baseURL: "",
  baseURL: "http://101.201.67.76:8060",
  timeout: 30000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    NProgress.start();
    config.headers["Authorization"] = getToken();
    config.headers["Content-Type"] = "application/json";
    config.headers["Cache-Control"] = "no-cache";
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;

    NProgress.done(); // 结束Progress
    // if the custom code is not 200, it is judged as an error.
    if (response.status !== 200) {
      Message({
        message: res.message || "网络错误",
        type: "error",
        duration: 5 * 1000
      });
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      if (
        res.strMsId &&
        (res.strMsId == "5001" ||
          res.strMsId == "5002" ||
          res.strMsId == "5003")
      ) {
        MessageBox.confirm(res.strMS || "网络错误", "错误", {
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          store.dispatch("User/resetToken").then(() => {
            location.reload();
          });
        });
      }
      if (res.strMsId && res.strMsId == "5004") {
        Message({
          message: res.strMS,
          type: "error",
          duration: 5 * 1000
        });
      }
      return res;
    }
  },
  error => {
    console.log("通讯错误" + error); // for debug
    Message({
      message: "网络错误",
      type: "error",
      duration: 5 * 1000
    });
    setTimeout(() => {
      store.dispatch("User/resetToken").then(() => {
        if (_this.$route.path !== "/Login") {
          location.reload();
        }
      });
    }, 2 * 1000);
    NProgress.done(); // 结束Progress
    return Promise.reject(error);
  }
);
/**
 * @description 提交
 * @param {String} url 地址 会自动拼接 /api/
 * @param {String} Action 请求事件名 默认是Get 参数 默认为{}
 * @param {Object} data 传递的参数 默认为{}
 * @return {Object} 返回结果
 */
export default async (url = "", Action = "Get", data = {}, MenuId = "-1") => {
  let jsTimeStamp = new Date().getTime();
  //得到当前路由的菜单ID
  if (_this && _this.$route.meta.activeMenu) {
    MenuId = _this.$route.meta.activeMenu;
  }
  //提交的参数
  let opt = { Action, data, MenuId, jsTimeStamp };
  // console.log("发送消息:" + url);
  // console.log("发送消息:" + JSON.stringify(opt));
  return service
    .post(`/api/${url}`, opt)
    .then(res => {
      // console.log("返回消息:" + JSON.stringify(res));
      return res;
    })
    .catch(err => {
      console.error("返回出错:" + err);
      return err;
    });
};
